#include "compress.h"
#include <errno.h>

int main(int argc,const char* argv[])
{
    int n;
    bool is_work = false;            //判断是否按照格式输入
    bool is_compress = true;
    if(argc > 1 && strlen(argv[1]) == 2 && ((!memcmp(argv[1], "-d", 2)) || (!memcmp(argv[1], "-c", 2)))) {
		is_work = true;
	}
    if(!is_work) {
		fprintf(stderr, "用法:\n  压缩:  %s -c file ...\n  解压:  %s -d file ...\n", argv[0], argv[0]);
		return 1;
	}

    if(!memcmp(argv[1], "-d", 2))
    {
        is_compress = false;
    }

    if(is_compress)
    {
        for(n=2; n<argc; n++)
        {
            FILE* rfp = fopen(argv[n], "rb");
            if(rfp == NULL) 
            {
			    fprintf(stderr, "File %s not exists, errno = %d, error = %s\n", argv[n], errno, strerror(errno));
			    continue;
		    }
            get_hafftree(rfp,argv[n]);
            compress_file(argv[n],rfp);
            fclose(rfp);
        }
        return 0;
    }
    //解压
    for(n=2; n<argc; n++)
    {
        FILE* rfp = fopen(argv[n],"rb");
        if(rfp == NULL) 
            {
			    fprintf(stderr, "File %s not exists, errno = %d, error = %s\n", argv[n], errno, strerror(errno));
			    continue;
		    }
        unsigned char val_arr[256] = {0};
	    size_t weight_arr[256] = {0};
        get_haffcode(argv[n],val_arr,weight_arr);
        TreeNode* root = init_tree(val_arr,weight_arr,sizeof(val_arr));
	    create_code(root);
        if(NULL == root)
        {
            printf("%s文件解压失败!\n",argv[n]);
            continue;
        }
        
        dp_file(root,rfp);
        fclose(rfp);
    }
	return 0;
}